package org.example.homework8.model;

import java.sql.*;

public class DBTest {

    String username;
    String password;
    public String Realname;

    public void getLoginInfo(String username, String password) {
        this.username = username;
        this.password = password;
    }



    public   void userLogin() {
        String url = "jdbc:mysql://localhost:3306/library_management?allowPublicRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai";
        String DBusername = "root"; // 你的数据库用户名
        String DBpassword = "123456"; // 你的数据库密码

        Connection conn = null; // 声明一个Connection对象
        PreparedStatement prep =null;
        ResultSet resultSet = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,DBusername,DBpassword);
            System.out.println("数据库连接成功！连接对象: " + conn);

            // 你的数据库操作代码
          String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
          prep = conn.prepareStatement(sql);
          prep.setString(1, username);
          prep.setString(2, password);
          resultSet = prep.executeQuery();

          while (resultSet.next()) {
              Realname  = resultSet.getString("name");
              System.out.println("User ID: " + resultSet.getInt("id"));
              System.out.println("Username: " + resultSet.getString("username"));
              System.out.println("Password: " + resultSet.getString("password"));
              System.out.println("Email: " + resultSet.getString("email"));
          }


        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 5. 关闭连接 (见下文)
            if (conn != null) {
                try {
                    conn.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (prep != null) {
                try {
                    prep.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
